package xhwl.insurance.ui.fragment;


import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.IOException;

import de.greenrobot.event.EventBus;
import xhwl.android.common.util.SPUtil;
import xhwl.android.common.util.StringUtil;
import xhwl.android.common.util.ToastUtil;
import xhwl.insurance.R;
import xhwl.insurance.customView.CircleImageView;
import xhwl.insurance.event.EventBean;
import xhwl.insurance.http.api.UnReadMsgCountApi;
import xhwl.insurance.http.api.UserInfoApi;
import xhwl.insurance.http.bean.CheckState;
import xhwl.insurance.http.bean.resp.MyInfoReturnResp;
import xhwl.insurance.http.bean.resp.UnReadMsgResp;
import xhwl.insurance.ui.CardDealListActivity;
import xhwl.insurance.ui.CustomerServiceActivity;
import xhwl.insurance.ui.MessageCenterActivity;
import xhwl.insurance.ui.MySetUpActivity;
import xhwl.insurance.ui.PerformanceActivity;
import xhwl.insurance.ui.PersonalCenterActivity;
import xhwl.insurance.util.BitmapUtil;
import xhwl.insurance.util.ImgTools;
import xhwl.insurance.util.ImmerseUtil;
import xhwl.insurance.util.XHLog;
import xhwl.retrofitrx.HttpException;
import xhwl.retrofitrx.HttpManager;
import xhwl.retrofitrx.OnNextListener;



public class MineFragment extends BaseFragment implements View.OnClickListener {
    private LinearLayout mine;
//    private LinearLayout mydycg;
    private LinearLayout myyj;
    private LinearLayout kf_phone;
    private LinearLayout setting;
    private CircleImageView touxiang;
    private ImageView iv_bell_info;
    private TextView name_tv, phone;
    private RelativeLayout info_rly,rl_blue_background;
    private TextView state_check_flag;
    private LinearLayout myCertification;
    private String checkCode;
    LinearLayout myCardDealList;
    LinearLayout llCode;
    Dialog shareDialog;
    TextView tvUnRead;
    private String member_pic;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        checkCode = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.CHECK_FLAG, "");
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_mine, null);
        return view;
    }

    @Override
    protected void initView(View view) {
        tvUnRead= (TextView) view.findViewById(R.id.tvUnRead);
        tvUnRead.setVisibility(View.GONE);
        mine = (LinearLayout) view.findViewById(R.id.mine);
        myyj = (LinearLayout) view.findViewById(R.id.myyj);
        kf_phone = (LinearLayout) view.findViewById(R.id.kf_phone);
        setting = (LinearLayout) view.findViewById(R.id.setting);
        myCertification = (LinearLayout) view.findViewById(R.id.myCertification);
        touxiang = (CircleImageView) view.findViewById(R.id.touxiang);
        iv_bell_info = (ImageView) view.findViewById(R.id.iv_bell_info);
        phone = (TextView) view.findViewById(R.id.phone);
        name_tv = (TextView) view.findViewById(R.id.name_tv);
        state_check_flag = (TextView) view.findViewById(R.id.state_check_flag);
        info_rly = (RelativeLayout) view.findViewById(R.id.info_rly);
        rl_blue_background = (RelativeLayout) view.findViewById(R.id.rl_blue_background);
        myCardDealList = (LinearLayout) view.findViewById(R.id.myCardDealList);
        llCode= (LinearLayout) view.findViewById(R.id.llCode);
        immerseUtil=new ImmerseUtil(getActivity());
        immerseUtil.setImmerseLayout(rl_blue_background);
    }

    @Override
    protected void initListener() {
        myyj.setOnClickListener(this);
        kf_phone.setOnClickListener(this);
        setting.setOnClickListener(this);
        myCertification.setOnClickListener(this);
        myCardDealList.setOnClickListener(this);
        llCode.setOnClickListener(this);
        iv_bell_info.setOnClickListener(this);
        touxiang.setOnClickListener(this);
        name_tv.setOnClickListener(this);
        phone.setOnClickListener(this);
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
        getUnReadMsgCount();
    }
    private void getUnReadMsgCount(){
        String memberId = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID,"");
        if (StringUtil.isEmpty(memberId)) {
            return;
        }
        UnReadMsgCountApi api=new UnReadMsgCountApi(memberId);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<UnReadMsgResp>() {
            @Override
            public void onNext(UnReadMsgResp resp) {
                if(resp!=null&&!StringUtil.isEmpty(resp.NUM)){
                    if(!"0".equals(resp.NUM)){
                        tvUnRead.setVisibility(View.VISIBLE);
                        tvUnRead.setText(resp.NUM);
                    }
                    else{
                        tvUnRead.setVisibility(View.GONE);
                    }
                }
            }
        });
    }
    @Override
    protected void loadData() {
    }

    @Override
    protected void processOper() {
        super.processOper();
        CheckState checkState = new CheckState(checkCode);
        state_check_flag.setText(checkState.getMsg());
        state_check_flag.setTextColor(getResources().getColor(checkState.getTextColor()));
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.touxiang://点击头像进入个人中心
                startActivity(new Intent(getActivity(), PersonalCenterActivity.class));
                break;
            case R.id.name_tv://点击姓名进入个人中心
                startActivity(new Intent(getActivity(), PersonalCenterActivity.class));
                break;
            case R.id.phone://点击手机号码也进入个人中心
                startActivity(new Intent(getActivity(), PersonalCenterActivity.class));
                break;
            case R.id.myyj://HMO 售卡统计
                startActivity(new Intent(getContext(), PerformanceActivity.class));
                break;
            case R.id.kf_phone://客服服务
                getActivity().startActivity(new Intent(getActivity(), CustomerServiceActivity.class)
                        .putExtra("BACK_STATE","0"));

                break;
            case R.id.setting:
                getActivity().startActivity(new Intent(getActivity(), MySetUpActivity.class));

                break;
            case R.id.myCertification:
                break;
            case R.id.myCardDealList://处理列表
                getActivity().startActivity(new Intent(getActivity(), CardDealListActivity.class));
                break;
            case R.id.llCode://推荐二维码
                showDialog();
                break;
            case R.id.iv_bell_info://消息
                getActivity().startActivity(new Intent(getActivity(), MessageCenterActivity.class)
                        .putExtra("BACK_STATE","0"));
                break;
            default:
                break;
        }
    }

    private void showDialog() {
//        if(shareDialog==null){
        shareDialog = new AlertDialog.Builder(mActivity).create();
        shareDialog.show();
        //下面代码为设置dialog弹出设置（dialog全屏显示，背景透明度）
        Window window = shareDialog.getWindow();
        WindowManager.LayoutParams lp = window.getAttributes();
        lp.width = WindowManager.LayoutParams.MATCH_PARENT;
        lp.height = WindowManager.LayoutParams.MATCH_PARENT;
        lp.alpha = 0.9f;
        window.setAttributes(lp);
        window.setContentView(R.layout.dialog_share);

        LinearLayout llSave = (LinearLayout) shareDialog.findViewById(R.id.llSave);
        LinearLayout llWX = (LinearLayout) shareDialog.findViewById(R.id.llWX);
        LinearLayout llPYQ = (LinearLayout) shareDialog.findViewById(R.id.llPYQ);
        ImageView ivClose = (ImageView) shareDialog.findViewById(R.id.ivClose);
        ImageView ivShareImage = (ImageView) shareDialog.findViewById(R.id.ivShareImage);

        ivClose.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                shareDialog.dismiss();
            }
        });
        final UMImage image = new UMImage(mActivity, R.drawable.erweima);
            //部分平台需要缩略图，暂不设置
//        UMImage thumb =  new UMImage(this, R.drawable.thumb);
//        image.setThumb(thumb);
        llWX.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(mActivity)
                        .setPlatform(SHARE_MEDIA.WEIXIN)
                        .setCallback(shareListener)
//                        .withText("hello")
                        .withMedia(image)
                        .share();
            }
        });
        llPYQ.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                new ShareAction(mActivity)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .setCallback(shareListener)
//                        .withText("hello")
                        .withMedia(image)
                        .share();
            }
        });
        llSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveImage();
            }
        });
    }

    private void saveImage() {
        Bitmap bitmap= BitmapFactory.decodeResource(mActivity.getResources(), R.drawable.erweima);
        try {
            BitmapUtil.saveFile(mActivity,bitmap,System.currentTimeMillis()+".png");
            ToastUtil.showToast(mActivity,"保存成功！");
            if(shareDialog!=null&&shareDialog.isShowing()){
                shareDialog.dismiss();
            }
        } catch (IOException e) {
            e.printStackTrace();
            ToastUtil.showToast(mActivity,"保存失败！");
        }
    }

    private UMShareListener shareListener = new UMShareListener() {

        /**
         * @descrption 分享成功的回调
         * @param platform 平台类型
         */
        @Override
        public void onResult(SHARE_MEDIA platform) {
            ToastUtil.showToast(mActivity,"分享成功！");
            if(shareDialog!=null&&shareDialog.isShowing()){
                shareDialog.dismiss();
            }
        }

        /**
         * @descrption 分享失败的回调
         * @param platform 平台类型
         * @param t 错误原因
         */
        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            ToastUtil.showToast(mActivity,"分享失败！");
        }

        /**
         * @descrption 分享取消的回调
         * @param platform 平台类型
         */
        @Override
        public void onCancel(SHARE_MEDIA platform) {
            ToastUtil.showToast(mActivity,"取消分享");

        }
    };

    private void getUserInfo() {
        String member_id = SPUtil.getPersonInfoSp().getString(SPUtil.SPPersonInfo.MEMBER_ID, "");
        UserInfoApi api = new UserInfoApi(member_id);
        HttpManager.getInstance().dealHttp(this, api, new OnNextListener<MyInfoReturnResp>() {

            @Override
            public void onNext(MyInfoReturnResp resp) {
                try {
                    SharedPreferences sp = SPUtil.getPersonInfoSp();
                    SharedPreferences.Editor editor = sp.edit();

                    member_pic = resp.getMEMBER_PIC();
                    editor.putString(SPUtil.SPPersonInfo.MEMBER_PIC, resp.getMEMBER_PIC());
                    editor.putString(SPUtil.SPPersonInfo.MEMBER_SEX, resp.getMEMBER_SEX());
                    editor.putString(SPUtil.SPPersonInfo.MEMBER_NAME, resp.getMEMBER_NAME());
                    editor.putString(SPUtil.SPPersonInfo.MEMBER_MOBILE, resp.getMEMBER_MOBILE());
                    editor.commit();
                    ImgTools.getInstance().getRadiusImgFromNetByUrl(resp.getMEMBER_PIC(), touxiang, R.drawable.touxiang, 90);
                    if ("null".equals(resp.getMEMBER_NAME()) || null == resp.getMEMBER_NAME() || "".equals(resp.getMEMBER_NAME())){
                        name_tv.setText(resp.getMEMBER_MOBILE());
                    }else {
                        name_tv.setText(resp.getMEMBER_NAME());
                    }
                    phone.setText(resp.getMEMBER_MOBILE());
                } catch (Exception e) {
                    XHLog.e(e.getMessage());
                }
            }

            @Override
            public void onError(HttpException ex) {
                super.onError(ex);
            }
        });
    }

   public void onEvent(EventBean eventBean){
       if (null != eventBean){
           getUserInfo();
       }
   }
}
